<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
</head>

<body>
    <div id="maximum">
        <h1>真划算</h1>
        <br>
        <table cellpadding="0" cellspacing="0">
            <thead style="border: none; background-color: #cccccc;">
                <tr style="border: none;">
                    <th>商品</th>
                    <th style="border-left: 2px solid #dbdbdb;">单价（元）</th>
                    <th style="border-left: 2px solid #dbdbdb;">颜色</th>
                    <th style="border-left: 2px solid #dbdbdb;">库存</th>
                    <th style="border-left: 2px solid #dbdbdb;">好评率</th>
                    <th style="border-left: 2px solid #dbdbdb;">操作</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>
    <br />
    <div id="Two_maximum">
        <h1>购物车</h1>
        <br>
        <table border="1" cellpadding="0" cellspacing="0">
            <thead style="border: none; background-color: #cccccc;">
                <tr style="border: none;">
                    <th>商品</th>
                    <th style="border-left: 2px solid #dbdbdb;">单价（元）</th>
                    <th style="border-left: 2px solid #dbdbdb;">数量</th>
                    <th style="border-left: 2px solid #dbdbdb;">金额</th>
                    <th style="border-left: 2px solid #dbdbdb;">删除</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
        <br>
        <h3>总计：<span>0</span>￥</h3>
    </div>
</body>
<script>
    //页面加载完毕之后
    window.onload = function () {
        //获取商品列表数据
        let goodsList = getGoodsList()
        //渲染商品列表
        renderGoodsList(goodsList)
        //获取购物车数据
        let shopCarList = getShopCarList()
        //渲染购物车
        renderShopCar(shopCarList)

        document
            .querySelector('#maximum tbody')
            .addEventListener('click', addShopCarFun)
        document
            .querySelector('#Two_maximum tbody')
            .addEventListener('click', downShopCarFun)
        document
            .querySelector('#Two_maximum tbody')
            .addEventListener('change', downShopCarFun)
    }
    //获取商品列表数据
    function getGoodsList() {
        let data = localStorage.getItem('goodsList')
        if (data) {
            return JSON.parse(data)
        } else {
            return [
                {
                    id: 1,
                    goodsName: '苹果',
                    price: 10,
                    color: 'red',
                    stock: 50,
                    goodRate: 49,
                },
                {
                    id: 2,
                    goodsName: '香蕉',
                    price: 15,
                    color: '黄色',
                    stock: 50,
                    goodRate: 49,
                },
                {
                    id: 3,
                    goodsName: '哈密瓜',
                    price: 20,
                    color: '绿色',
                    stock: 50,
                    goodRate: 49,
                },
            ]
        }
    }
    //渲染商品列表
    function renderGoodsList(data) {
        let html = ''
        data.forEach((item, index) => {
            html += `<tr>
                                    <td>${item.goodsName}</td>
                                    <td>${item.price}</td>
                                    <td>${item.color}</td>
                                    <td>${item.stock}</td>
                                    <td>${item.goodRate}</td>
                                    <td><button index="${index}">加入购物车</button></td>
                                </tr>`
        })
        document.querySelector('#maximum tbody').innerHTML = html
    }

    //获取购物车列表
    function getShopCarList() {
        let data = localStorage.getItem('shopCarList')
        if (data) {
            return JSON.parse(data)
        } else {
            return []
        }
    }

    //渲染购物车列表
    function renderShopCar(data) {
        let html = ''
        data.forEach((item, index) => {
            html += ` <tr>
                                <td>${item.goodsName}</td>
                                <td>${item.price}</td>
                                <td>
                                    <button class="btn" index="${index}">-</button>
                                    <input index="${index}" type="text" value="${item.num}" />
                                    <button class="btn" index="${index}">+</button>
                                </td>
                                <td>${item.price * item.num}</td>
                                <td><button class='del' index="${index}">删除</button></td>
                            </tr>`
        })
        document.querySelector('#Two_maximum tbody').innerHTML = html
        countPrice()
    }
    function countPrice() {
        let shopCarList = getShopCarList()
        let price = 0
        shopCarList.forEach((item) => {
            price += item.price * item.num
        })
        document.querySelector('#Two_maximum span').innerHTML = price
    }

    function downShopCarFun() {
        if (event.target.nodeName == 'BUTTON') {
            let index = event.target.getAttribute('index')
            let shopCarList = getShopCarList()
            let goodsList = getGoodsList()
            if (event.target.innerHTML == '-') {
                if (shopCarList[index].num < 2) {
                    alert('不能再减了最少买一件')
                    return
                }
                shopCarList[index].num--
                let gIndex = goodsList.findIndex((item) => {
                    return item.id == shopCarList[index].id
                })
                goodsList[gIndex].stock++
            }
            if (event.target.innerHTML == '+') {
                let gIndex = goodsList.findIndex((item) => {
                    return item.id == shopCarList[index].id
                })
                if (goodsList[gIndex].stock == 0) {
                    alert('库存不足')
                    return
                }
                shopCarList[index].num++
                goodsList[gIndex].stock--
            }
            if (event.target.innerHTML == '删除') {
                let gIndex = goodsList.findIndex((item) => {
                    return item.id == shopCarList[index].id
                })
                goodsList[gIndex].stock += shopCarList[index].num
                shopCarList.splice(index, 1)
            }
            localStorage.setItem('shopCarList', JSON.stringify(shopCarList))
            localStorage.setItem('goodsList', JSON.stringify(goodsList))
            renderShopCar(shopCarList)
            renderGoodsList(goodsList)
        }
        if (event.target.nodeName == 'INPUT' && event.type != 'click') {
            let n = event.target.value
            let reg = /^\d+$/
            let shopCarList = getShopCarList()
            let index = event.target.getAttribute('index')
            let goodsList = getGoodsList()
            let gIndex = goodsList.findIndex((item) => {
                return item.id == shopCarList[index].id
            })
            if (!reg.test(n)) {
                alert('请输入数字')
                event.target.value = shopCarList[index].num
                return
            }
            if (+event.target.value < shopCarList[index].num) {
                let cha = shopCarList[index].num - event.target.value
                goodsList[gIndex].stock += cha
                shopCarList[index].num = event.target.value
            } else if (goodsList[gIndex].stock < event.target.value) {
                alert('库存只剩' + goodsList[gIndex].stock + '件')
                event.target.value =
                    +shopCarList[index].num + +goodsList[gIndex].stock
                goodsList[gIndex].stock = 0
                shopCarList[index].num = event.target.value
            }

            localStorage.setItem('shopCarList', JSON.stringify(shopCarList))
            localStorage.setItem('goodsList', JSON.stringify(goodsList))
            renderShopCar(shopCarList)
            renderGoodsList(goodsList)
        }
    }
    //加入购物车函数
    function addShopCarFun() {
        if (event.target.nodeName == 'BUTTON') {
            let index = event.target.getAttribute('index')
            let goodsList = getGoodsList()
            let shopCarList = getShopCarList()
            //判断购物车中是否有该商品
            let sIndex = shopCarList.findIndex((item) => {
                return item.id == goodsList[index].id
            })
            if (sIndex == -1) {
                shopCarList.push({
                    id: goodsList[index].id,
                    goodsName: goodsList[index].goodsName,
                    price: goodsList[index].price,
                    num: 1,
                })
                goodsList[index].stock--
            } else {
                if (goodsList[index].stock == 0) {
                    alert('库存不足')
                    return
                }
                shopCarList[sIndex].num++
                goodsList[index].stock--
            }
            //保存购物车数据
            localStorage.setItem('shopCarList', JSON.stringify(shopCarList))
            localStorage.setItem('goodsList', JSON.stringify(goodsList))
            renderShopCar(shopCarList)
            renderGoodsList(goodsList)
        }
    }


</script>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    body {
        display: flex;
        flex-wrap: wrap;
    }

    #maximum {
        text-align: center;
        margin: auto;
    }

    #maximum tr th {
        height: 3rem;
        /* border-bottom: none;
            border-top: none;
            border-right: none; */
        border: none;
    }

    #maximum button {
        width: 6rem;
        height: 2rem;
        border: #ccc;
        border-radius: 0.3rem;
        /* background-color: #dddddd; */
    }

    table {
        width: 800px;
        border: 1px solid #dddddd;

    }

    td {
        text-align: center;
        height: 3rem;
        border: 1px solid #dddddd;
    }

    #Two_maximum {
        text-align: center;
        margin: auto;
        margin-top: 2rem;
    }

    #Two_maximum tr th {
        height: 3rem;
        border: none;
    }

    #Two_maximum input {
        width: 8rem;
        height: 2rem;
        text-align: center;
    }

    .btn {
        width: 2rem;
        height: 2rem;
    }

    .del {
        width: 3rem;
        height: 2rem;
        border: #ccc;
        border-radius: 0.3rem;
    }
</style>

</html>